/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ar.com.remiseria.frame;

import ar.com.remiseria.bo.ClienteBO;
import ar.com.remiseria.entities.Cliente;
import ar.com.remiseria.utils.Constantes;
import ar.com.remiseria.utils.PropertiesReader;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author mcvalls
 */
public class ABMClientesFrame extends javax.swing.JFrame {

    List<Cliente> clientesLista = new ArrayList<Cliente>();
    private int paginaActual = 1;
    private int paginasTotales = 1;
    
    /**
     * Creates new form ABMClienteesFrame
     */
    public ABMClientesFrame() {
        initComponents();
        this.getClientes();
        this.verificarPaginado();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        clientesTable = new javax.swing.JTable();
        nuevoClienteBtn = new javax.swing.JButton();
        bajaClienteBtn = new javax.swing.JButton();
        volverBtn = new javax.swing.JButton();
        editarClienteBtn = new javax.swing.JButton();
        pagAnteriorBtn = new javax.swing.JButton();
        paginasLbl = new javax.swing.JLabel();
        pagSiguienteBtn = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        editarMenuBtn = new javax.swing.JMenuItem();
        bajaMenuBtn = new javax.swing.JMenuItem();
        volverMenuBtn = new javax.swing.JMenuItem();
        nuevoMenuBtn = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        clientesTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null}
            },
            new String [] {
                "Codigo Cliente", "Nombre", "Apellido", "Telefono", "Documento", "Domicilio"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Long.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        clientesTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        jScrollPane1.setViewportView(clientesTable);

        nuevoClienteBtn.setText("Nuevo Cliente");
        nuevoClienteBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nuevoClienteBtnActionPerformed(evt);
            }
        });

        bajaClienteBtn.setText("Baja Cliente");
        bajaClienteBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bajaClienteBtnActionPerformed(evt);
            }
        });

        volverBtn.setText("Volver");
        volverBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                volverBtnActionPerformed(evt);
            }
        });

        editarClienteBtn.setText("Editar Cliente");
        editarClienteBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editarClienteBtnActionPerformed(evt);
            }
        });

        pagAnteriorBtn.setText("Ant");
        pagAnteriorBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pagAnteriorBtnActionPerformed(evt);
            }
        });

        paginasLbl.setText("Pagina X de Y");

        pagSiguienteBtn.setText("Sig");
        pagSiguienteBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pagSiguienteBtnActionPerformed(evt);
            }
        });

        jMenu1.setText("Archivo");

        editarMenuBtn.setText("Nuevo...");
        editarMenuBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editarMenuBtnActionPerformed(evt);
            }
        });
        jMenu1.add(editarMenuBtn);

        bajaMenuBtn.setText("Editar...");
        bajaMenuBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bajaMenuBtnActionPerformed(evt);
            }
        });
        jMenu1.add(bajaMenuBtn);

        volverMenuBtn.setText("Borrar...");
        volverMenuBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                volverMenuBtnActionPerformed(evt);
            }
        });
        jMenu1.add(volverMenuBtn);

        nuevoMenuBtn.setText("Volver");
        nuevoMenuBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nuevoMenuBtnActionPerformed(evt);
            }
        });
        jMenu1.add(nuevoMenuBtn);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 750, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(volverBtn))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(nuevoClienteBtn)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(editarClienteBtn)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bajaClienteBtn))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(pagAnteriorBtn)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(paginasLbl)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(pagSiguienteBtn)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pagAnteriorBtn)
                    .addComponent(paginasLbl)
                    .addComponent(pagSiguienteBtn))
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nuevoClienteBtn)
                    .addComponent(editarClienteBtn)
                    .addComponent(bajaClienteBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(volverBtn)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nuevoClienteBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoClienteBtnActionPerformed
        this.irANuevoCliente();
    }//GEN-LAST:event_nuevoClienteBtnActionPerformed

    private void editarClienteBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editarClienteBtnActionPerformed
        this.irAEditarCliente();
    }//GEN-LAST:event_editarClienteBtnActionPerformed

    private void volverBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_volverBtnActionPerformed
        MenuPrincipalFrame mpf = new MenuPrincipalFrame();
        mpf.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_volverBtnActionPerformed

    private void bajaClienteBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bajaClienteBtnActionPerformed
        this.bajaCliente();
    }//GEN-LAST:event_bajaClienteBtnActionPerformed

    private void editarMenuBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editarMenuBtnActionPerformed
        nuevoClienteBtnActionPerformed(evt);
    }//GEN-LAST:event_editarMenuBtnActionPerformed

    private void bajaMenuBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bajaMenuBtnActionPerformed
        editarClienteBtnActionPerformed(evt);
    }//GEN-LAST:event_bajaMenuBtnActionPerformed

    private void volverMenuBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_volverMenuBtnActionPerformed
        bajaClienteBtnActionPerformed(evt);
    }//GEN-LAST:event_volverMenuBtnActionPerformed

    private void nuevoMenuBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoMenuBtnActionPerformed
        volverBtnActionPerformed(evt);
    }//GEN-LAST:event_nuevoMenuBtnActionPerformed

    private void pagAnteriorBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pagAnteriorBtnActionPerformed
        paginaActual = paginaActual - 1;
        this.getClientes();
        this.verificarPaginado();
    }//GEN-LAST:event_pagAnteriorBtnActionPerformed

    private void pagSiguienteBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pagSiguienteBtnActionPerformed
        paginaActual = paginaActual + 1;
        this.getClientes();
        this.verificarPaginado();
    }//GEN-LAST:event_pagSiguienteBtnActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ABMClientesFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ABMClientesFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ABMClientesFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ABMClientesFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ABMClientesFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bajaClienteBtn;
    private javax.swing.JMenuItem bajaMenuBtn;
    private javax.swing.JTable clientesTable;
    private javax.swing.JButton editarClienteBtn;
    private javax.swing.JMenuItem editarMenuBtn;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton nuevoClienteBtn;
    private javax.swing.JMenuItem nuevoMenuBtn;
    private javax.swing.JButton pagAnteriorBtn;
    private javax.swing.JButton pagSiguienteBtn;
    private javax.swing.JLabel paginasLbl;
    private javax.swing.JButton volverBtn;
    private javax.swing.JMenuItem volverMenuBtn;
    // End of variables declaration//GEN-END:variables

    private void getClientes() {
        ClienteBO clienteBO = new ClienteBO();
        List<Cliente> losClientes = new ArrayList<Cliente>();
        
        DefaultTableModel modelo = new DefaultTableModel();
        modelo.addColumn("Codigo Cliente");
        modelo.addColumn("Nombre");
        modelo.addColumn("Apellido");
        modelo.addColumn("Telefono");
        modelo.addColumn("Documento");
        modelo.addColumn("Domicilio");
        
        try{
            losClientes = clienteBO.getAllClientes(paginaActual);
        }catch(Exception ex){
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
        
        if(losClientes != null && !losClientes.isEmpty()){
            for(Cliente cliente : losClientes){
                Object[] clientes = new Object[6];
                clientes[0] = cliente.getCodigo();
                clientes[1] = cliente.getNombre();
                clientes[2] = cliente.getApellido();
                clientes[3] = cliente.getTelefono();
                
                clientes[4] = cliente.getDocumento().getTipoDeDocumento().getDescripcion()+
                                " - "+ cliente.getDocumento().getNumero();
                
                String domicilioFormateado = cliente.getDomicilio().getCalle();
                if(cliente.getDomicilio().getNumero() != null){
                    domicilioFormateado+=" "+cliente.getDomicilio().getNumero();
                }
                if(cliente.getDomicilio().getPiso() != null){
                    domicilioFormateado+=" Piso "+cliente.getDomicilio().getPiso();
                }
                if(cliente.getDomicilio().getDepartamento() != null){
                    domicilioFormateado+=" Dpto "+cliente.getDomicilio().getDepartamento();
                }
                if(cliente.getDomicilio().getCodigoPostal() != null){
                    domicilioFormateado+=",C.P "+cliente.getDomicilio().getCodigoPostal();
                }
                if(cliente.getDomicilio().getLocalidad() != null){
                    domicilioFormateado+= " - "+cliente.getDomicilio().getLocalidad();
                }
                if(cliente.getDomicilio().getProvincia() != null){
                    domicilioFormateado+=", "+cliente.getDomicilio().getProvincia();
                }
                
                clientes[5] = domicilioFormateado;
                                
                modelo.addRow(clientes);
                clientesLista.add(cliente);
            }
            
        }
        clientesTable.setModel(modelo);
        
    }

    private void irANuevoCliente() {
        AltaClienteFrame acf = new AltaClienteFrame();
        acf.setVisible(true);
        this.dispose();
    }

    private void irAEditarCliente() {
        int index = clientesTable.getSelectedRow() + (Constantes.PAG_MAX_RESULTS * (paginaActual - 1));
        if(index < 0){
            JOptionPane.showMessageDialog(this, 
                    PropertiesReader.getInstance().getApplicationMessage("error.abm.cliente.noseleccionado"));
        }else{
            Cliente cliente = clientesLista.get(index);
            
            EditarClienteFrame ecf = new EditarClienteFrame(cliente);
            ecf.setVisible(true);
            this.dispose();
        }
    }

    private void bajaCliente() {
        int index = clientesTable.getSelectedRow() + (Constantes.PAG_MAX_RESULTS * (paginaActual - 1));
        if(index < 0){
            JOptionPane.showMessageDialog(this, 
                    PropertiesReader.getInstance().getApplicationMessage("error.abm.cliente.noseleccionado"));
        }else{
            int confirmaBaja = JOptionPane.showConfirmDialog(this,
                    PropertiesReader.getInstance().getApplicationMessage("alerta.abm.cliente.confirmabaja"),
                    "Mensaje", JOptionPane.YES_NO_CANCEL_OPTION);
            if(confirmaBaja == JOptionPane.YES_OPTION){
                Cliente cliente = clientesLista.get(index);
                try{
                    ClienteBO clienteBO = new ClienteBO();
                    clienteBO.deleteCliente(cliente);
                    this.getClientes();
                }catch(Exception ex){
                    JOptionPane.showMessageDialog(this, ex);
                    ex.printStackTrace();
                }
            }
        }
    }

    private void verificarPaginado() {
        ClienteBO clienteBO = new ClienteBO();
        int clientesTotales = 0;
        
        try{
            clientesTotales = clienteBO.getChoferesCount(); 
        }catch(Exception ex){
            ex.printStackTrace();
        }
        
        if(clientesTotales != 0){
            int cantidadPaginas = clientesTotales % Constantes.PAG_MAX_RESULTS;
            if(cantidadPaginas == 0){
                cantidadPaginas = clientesTotales / Constantes.PAG_MAX_RESULTS;
            }else{
                cantidadPaginas = (clientesTotales / Constantes.PAG_MAX_RESULTS) + 1;
            }
            paginasTotales = cantidadPaginas;
        }
        
        paginasLbl.setText("Pagina "+paginaActual+" de "+paginasTotales);
        
        if(paginaActual == 1){
            pagAnteriorBtn.setEnabled(false);
        }else{
            pagAnteriorBtn.setEnabled(true);
        }
        
        if(paginaActual == paginasTotales){
            pagSiguienteBtn.setEnabled(false);
        }else{
            pagSiguienteBtn.setEnabled(true);
        }
    }

}
